<template>
    <div class="goodsAdd_container">
        <el-row type="flex" align="middle">            
            <el-col :span="1" :offset="8">
                <i class="el-icon-sell"></i>
            </el-col>
            <el-col :span="3">
                <h1>添加商品</h1>
            </el-col>
            <el-col :span="1" :offset="9">
                <el-button
                    type="danger"
                    size="small"
                    plain
                    @click="$router.push('/goods')"
                >
                取消添加
                <i class="el-icon-close"></i>
                </el-button>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="19" :offset="1">
                    <el-tabs type="border-card" v-model="actionPageStr">
                        <el-tab-pane name="1" :disabled="infoFormFirst">
                            <span slot="label"><i class="el-icon-document"></i> 基本信息</span>
                            <el-form
                                :model="goodsAddInfoForm"
                                :rules="goodsAddInfoFormRules"
                                ref="goodsAddInfoFormRef"
                                label-position="right"
                                label-width="80px"
                                status-icon
                            >
                                <el-row>
                                    <el-col :span="22" :offset="1">
                                        <el-form-item label="商品名称" prop="newGoodsName">
                                            <el-input
                                                v-model="goodsAddInfoForm.newGoodsName"
                                                clearable
                                                placeholder="请输入商品名称"
                                                :maxlength="60"
                                                show-word-limit
                                            >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="7" :offset="1">
                                        <el-form-item label="商品价格"  prop="newGoodsPrice">
                                            <el-input
                                                v-model="goodsAddInfoForm.newGoodsPrice"
                                                clearable
                                                placeholder="请输入价格"
                                            >
                                            <template slot="append">元</template>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7" :offset="1">
                                        <el-form-item label="商品重量" prop="newGoodsWeight">
                                            <el-input 
                                                v-model.number="goodsAddInfoForm.newGoodsWeight"
                                                clearable 
                                                placeholder="请输入重量"
                                            >
                                            <template slot="append">kg</template>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="6" :offset="1">
                                        <el-form-item label="商品数量" prop="newGoodsNum">
                                            <el-input-number
                                                v-model="goodsAddInfoForm.newGoodsNum"
                                                controls-position="right"
                                                :min="1"
                                                :max="9999"
                                                placeholder="请输入数量"
                                                style="width:100%"
                                            >
                                            </el-input-number>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="22" :offset="1">
                                        <el-form-item label="商品介绍" prop="newGoodsCateIntroduce">
                                        <el-input
                                            type="textarea"
                                            :autosize="{ minRows: 3, maxRows: 6}"
                                            :maxlength="600"
                                            resize="none"
                                            clearable
                                            placeholder="请输入商品介绍内容"
                                            v-model="goodsAddInfoForm.newGoodsCateIntroduce">
                                        </el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="11" :offset="1">
                                        <el-form-item label="商品分类" prop="newGoodsCate">
                                                <el-cascader
                                                    clearable
                                                    v-model="goodsAddInfoForm.newGoodsCate"
                                                    :options="goodsCateList"
                                                    :props="cascaderProps"
                                                    @change="changeGoodsCate"
                                                    style="width:100%"
                                                >
                                            </el-cascader>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="11" :offset="1" class="newFormButton">
                                        <el-form-item>
                                            <el-button-group>
                                                <el-button
                                                    type="primary"
                                                    size="small"
                                                    @click="toNextForm"
                                                >
                                                下一步
                                                </el-button>
                                                <el-button
                                                    type="info"
                                                    size="small"
                                                    @click="resetInfoForm"
                                                >
                                                重 置
                                                </el-button>
                                            </el-button-group>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane name="2" :disabled="staticFormFirst">
                            <span slot="label"><i class="el-icon-price-tag"></i> 商品属性</span>
                            <el-form label-position="right" label-width="11vw">
                            <el-row v-if="goodsStaticParamsList.length != 0" class="taHeight">
                                <el-col :span="10" :offset="1" v-for="sItem in goodsStaticParamsList" :key="sItem.attr_id">
                                    <el-form-item :label="sItem.attr_name">
                                        <el-input clearable v-model="sItem.attr_vals"></el-input>
                                    </el-form-item>                                    
                                </el-col>
                            </el-row>
                            <el-row v-else>
                                <el-col>
                                    <el-empty
                                        image="https://www.gstatic.com/android/keyboard/emojikitchen/20201001/u1f4f0/u1f4f0_u1f4f0.png"
                                        description="暂无预设商品属性，可直接下一步！"
                                    >
                                    </el-empty>
                                </el-col>
                            </el-row>
                            <el-row>
                                    <el-col :span="22" :offset="1" class="newFormButton">
                                        <el-form-item>
                                            <el-button-group>
                                                <el-button
                                                    type="primary"
                                                    size="small"
                                                    @click="backLastForm"
                                                >
                                                上一步
                                                </el-button>
                                                <el-button
                                                    type="primary"
                                                    size="small"
                                                    @click="toNextForm"
                                                >
                                                下一步
                                                </el-button>
                                                <el-button
                                                    type="info"
                                                    size="small"
                                                    @click="getgoodsStaticParams"
                                                >
                                                重 置
                                                </el-button>
                                            </el-button-group>
                                        </el-form-item>
                                    </el-col>
                            </el-row>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane name="3" :disabled="dynamicFormFirst">
                            <span slot="label"><i class="el-icon-discount"></i> 商品参数</span>
                            <el-form label-position="top">
                            <el-row v-if="goodsDynamicParamsList.length != 0">
                                <el-col :span="22" :offset="1" class="taHeight">
                                    <el-form-item
                                        v-for="dItem in goodsDynamicParamsList"
                                        :key="dItem.attr_id"
                                        :label="dItem.attr_name"
                                    >
                                        <el-checkbox-group v-model="dItem.attr_vals" v-if="dItem.copyList.length != 0">
                                            <el-checkbox
                                                v-for="(cbItem,index) in dItem.copyList"
                                                :key="index"
                                                :label="cbItem"
                                                border
                                                size="mini"
                                                :style="index | chooseColor"
                                            >
                                            </el-checkbox>
                                        </el-checkbox-group>
                                        <el-alert
                                            v-else
                                            title="暂无商品参数项"
                                            type="info"
                                            show-icon
                                            style="line-height:20px;width:11vw"
                                        >
                                        </el-alert>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row v-else>
                                <el-col>
                                    <el-empty
                                        image="https://www.gstatic.com/android/keyboard/emojikitchen/20201001/u1f4f0/u1f4f0_u1f4f0.png"
                                        description="暂无预设商品参数，可直接下一步！"
                                    >
                                    </el-empty>
                                </el-col>
                            </el-row>
                            <el-row>
                                    <el-col :span="22" :offset="1" class="newFormButton">
                                        <el-form-item>
                                            <el-button-group>
                                                <el-button
                                                    type="primary"
                                                    size="small"
                                                    @click="backLastForm"
                                                >
                                                上一步
                                                </el-button>
                                                <el-button
                                                    type="primary"
                                                    size="small"
                                                    @click="toNextForm"
                                                >
                                                下一步
                                                </el-button>
                                                <el-button
                                                    type="info"
                                                    size="small"
                                                    @click="getgoodsDynamicParams"
                                                >
                                                重 置
                                                </el-button>
                                            </el-button-group>
                                        </el-form-item>
                                    </el-col>
                            </el-row>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane name="4" :disabled="uploadPicsFormFirst">
                            <span slot="label"><i class="el-icon-picture-outline"></i> 商品图片</span>
                            <el-form>
                                <el-row>
                                    <el-col :span="22" :offset="1" class="taHeight">
                                        <el-form-item>
                                            <el-upload
                                                action="http://127.0.0.1:8888/api/private/v1/upload"
                                                ref="uploadPicsRef"
                                                :headers="headerObj"
                                                :on-preview="handlePreview"
                                                :on-remove="handleRemove"
                                                :before-upload="handleBeforeUpload"
                                                :on-success="handleSuccess"
                                                list-type="picture"
                                                accept=".png,.jpeg,.jpg,.gif"
                                                drag
                                                multiple
                                            >
                                                <div style="width:56vw">
                                                    <i class="el-icon-upload"></i>
                                                    <div class="el-upload__text" >
                                                        将图片拖到此处，或<em>点击上传</em>
                                                        <p style="font-size:10px;margin-top:-10px" class="el-upload__tip">要求格式:jpg/png/jpeg 支持多选</p>
                                                    </div>
                                                </div>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row type="flex" align="end">
                                    <el-col :span="3" :offset="1" class="bottomText">
                                        <p>已选择 <span style="color:#409eff">{{pics.length}}</span> 张图片</p>
                                    </el-col>
                                    <el-col :span="19">
                                        <el-form-item class="newFormButton">
                                            <el-button-group>
                                                <el-button
                                                    type="primary"
                                                    size="small"
                                                    @click="backLastForm"
                                                >
                                                上一步
                                                </el-button>
                                                <el-button
                                                    type="info"
                                                    size="small"
                                                    @click="resetPicsForm"
                                                >
                                                重 置
                                                </el-button>
                                                <el-button
                                                    type="success"
                                                    size="small"
                                                    @click="checkAddGoodsCateForm"
                                                >
                                                完 成
                                                </el-button>
                                            </el-button-group>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane name="5" style="text-align:center;line-height:10px" :disabled="finishFormFirst">
                            <span slot="label"><i class="el-icon-sell"></i> 添加完成</span>
                            <el-row>
                                <el-col>
                                    <i class="el-icon-circle-check" style="font-size:10vw;color:#5cde60"></i>
                                </el-col>
                            </el-row>
                            <el-row>
                                <p style="font-size:22px;font-weight:bold;color:#5cde60">添加成功</p>
                                <p style="font-size:14px;color:#5cde60">将在 <span style="font-size:14px;color:#dc4d41">{{countDown}}秒</span> 后自动返回商品列表</p>
                            </el-row>
                        </el-tab-pane>
                    </el-tabs>
                
            </el-col>
            <el-col :span="2" :offset="1" style="height: 58vh;margin-bottom:26px">
                <el-steps direction="vertical" :active="actionPage-1" finish-status="success">
                    <el-step title="基本信息" icon="el-icon-document"></el-step>
                    <el-step title="商品属性" icon="el-icon-price-tag"></el-step>
                    <el-step title="商品参数" icon="el-icon-discount"></el-step>
                    <el-step title="商品图片" icon="el-icon-picture-outline"></el-step>
                    <el-step title="添加完成" icon="el-icon-sell"></el-step>
                </el-steps>
            </el-col>
        </el-row>
        <div class="picsPreview" v-show="picsVisible" >
            <span class="closeBtn" @click="showPics">&times;</span>
            <el-image :src="picsPreviewUrl" class="image"></el-image>            
        </div>
    </div>
</template>

<script>
export default({
    name:'goodsadd',
    data(){
        var checkName = (rule, value, callback) => {
            if(isNaN(value)){
                callback();
            }else{
                callback(new Error('商品名称不能是纯数字！'));
            }
        };
        var checkPrice = (rule, value, callback) => {
            if(value) {
                let rePrice = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
                if(rePrice.test(value)) {
                    if(value > 999999999 || value < 0){
                        callback(new Error('商品价格应在合理范围值！'));
                    }else{
                        callback();
                    }
                    callback();
                }else{
                    callback(new Error('请输入合法的商品价格！'));
                }
            }else{
                callback();
            }
        };
        var checkWeight = (rule, value, callback) => {
            if(value) {
                let reWeight = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
                if(reWeight.test(value)) {
                    if(value > 999999 || value < 0){
                        callback(new Error('商品重量应在合理范围值！'));
                    }else{
                        callback();
                    }
                    callback();
                }else{
                    callback(new Error('请输入合法的商品重量！'));
                }
            }else{
                callback();
            }
        };

        return {
            actionPage:1,
            actionPageStr:'1',
            goodsAddInfoForm:{
                newGoodsName:'',
                newGoodsPrice:'',
                newGoodsWeight:'',
                newGoodsNum:1,
                newGoodsCate:[],
                newGoodsCatePush:[],
                newGoodsCateIntroduce:'',
            },
            goodsCateList:[],
            cascaderProps:{
                value: 'cat_id',
                label:'cat_name',
                children: 'children',
                expandTrigger:'hover',
            },
            goodsAddInfoFormRules:{
                newGoodsName:[
                    {
                        required: true,
                        message: '商品名称不能为空！',
                        trigger: 'blur'
                    },
                    {
                        max: 60,
                        message: '商品名称过长！',
                        trigger: 'blur'
                    },
                    {
                        validator: checkName,
                        trigger: 'blur'
                    },
                ],
                newGoodsPrice:[
                    {
                        required: true,
                        message: '商品价格不能为空！',
                        trigger: 'blur'
                    },
                    {
                        validator: checkPrice,
                        trigger: 'blur'
                    },
                ],
                newGoodsWeight:[
                    {
                        required: true,
                        message: '商品重量不能为空！',
                        trigger: 'blur'
                    },
                    {
                        validator: checkWeight,
                        trigger: 'blur'
                    },
                ],
                newGoodsNum:[
                    {
                        required: true,
                        message: '商品数量不能为空！',
                        trigger: 'blur'
                    },
                    {
                        type: 'number',
                        message: '数量必须为阿拉伯数字'
                    }
                ],
                newGoodsCate:[
                    {
                        required: true,
                        message: '商品分类不能为空！',
                        trigger: 'blur'
                    },
                ],
                newGoodsCateIntroduce:[
                    {
                        max: 600,
                        message: '商品介绍内容过长！请控制在600字符之间',
                        trigger: 'blur'
                    }
                ]

            },
            goodsStaticParamsList:[],
            goodsDynamicParamsList:[],
            headerObj:{
                Authorization:window.sessionStorage.getItem('token')
            },
            pics:[],
            picsPreviewUrl:'',
            picsVisible:false,

            attrs:[],
            infoFormFirst:false,
            staticFormFirst:true,
            dynamicFormFirst:true,
            uploadPicsFormFirst:true,
            finishFormFirst:true,

            countDown:3,
        }
    },
    created(){
        this.getgoodsCateList();
    },
    methods:{
        async getgoodsCateList(){
            const { data: res } = await this.$http.get('categories',{params:{type: 3}});
            if(res.meta.status == 200){
                this.goodsCateList = res.data;
            }else{
                return this.$message(
                    {
                        center:true,
                        showClose: true,
                        type: 'error',
                        duration:2000,
                        message: '获取商品分类失败！'
                    }
                )
            }
        },
        async changeGoodsCate(){
            if(this.goodsAddInfoForm.newGoodsCate.length == 2 || this.goodsAddInfoForm.newGoodsCate.length == 1)
            {
                this.goodsAddInfoForm.newGoodsCate = [];
                return this.$message(
                    {
                        center:true,
                        showClose: true,
                        type: 'warning',
                        duration:2000,
                        message: '仅能选择第三级商品分类!请重选！'
                    }
                )
            }
        },
        async getgoodsStaticParams(){
            if(this.goodsAddInfoForm.newGoodsCate.length == 3 && this.actionPageStr == '2'){
                let CateParamsID = this.goodsAddInfoForm.newGoodsCate[this.goodsAddInfoForm.newGoodsCate.length -1];
                const { data: res} = await this.$http.get(`categories/${CateParamsID}/attributes`,
                    {params:{sel:'only'}}
                );
                if(res.meta.status == 200){
                    this.goodsStaticParamsList = res.data
                }else{
                    return this.$message(
                        {
                            center:true,
                            showClose: true,
                            type: 'warning',
                            duration:2000,
                            message: '获取商品属性失败！'
                        }
                    )
                }
            }else{
                return this.$message(
                    {
                        center:true,
                        showClose: true,
                        type: 'warning',
                        duration:2000,
                        message: '获取商品属性失败！请检查是否已选择第三级商品分类！'
                    }
                )
            }
        },
        async getgoodsDynamicParams(){
            if(this.goodsAddInfoForm.newGoodsCate.length == 3 && this.actionPageStr == '3'){
                let CateParamsID = this.goodsAddInfoForm.newGoodsCate[this.goodsAddInfoForm.newGoodsCate.length -1];
                const { data: res} = await this.$http.get(`categories/${CateParamsID}/attributes`,
                    {params:{sel:'many'}}
                );
                if(res.meta.status == 200){
                    res.data.forEach(item => {
                        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
                        //作深度拷贝，显示用拷贝项，操作用数据项
                        item.copyList = item.attr_vals;
                    });
                    this.goodsDynamicParamsList = res.data
                }else{
                    return this.$message(
                        {
                            center:true,
                            showClose: true,
                            type: 'warning',
                            duration:2000,
                            message: '获取商品参数失败！'
                        }
                    )
                }
            }else{
                return this.$message(
                    {
                        center:true,
                        showClose: true,
                        type: 'warning',
                        duration:2000,
                        message: '获取商品参数失败！请检查是否已选择第三级商品分类！'
                    }
                )
            }
        },
        handlePreview(file){
            this.picsPreviewUrl = file.response.data.url;
            this.showPics()
        },
        showPics(){
            this.picsVisible = !this.picsVisible
        },
        handleRemove(file){
            try{
                const filePath = file.response.data.tmp_path;
                const picIndex = this.pics.findIndex(picPath => picPath.pic === filePath);
                this.pics.splice(picIndex,1);
            }catch(e){
                console.log('已删除错误格式的图片')
            }
            
        },
        handleBeforeUpload(file){
            var rePic = /\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
                if (!rePic.test(file.name)){
                    this.$message(
                        {
                            center:true,
                            showClose: true,
                            type: 'warning',
                            duration:2000,
                            message: '请上传格式是gif或jpeg或jpg或png的图片！'
                        }
                    );
                    return false;
                }
        },
        handleSuccess(response){
            const picinfo ={ pic:response.data.tmp_path };
            this.pics.push(picinfo)
        },
        resetInfoForm(){
            this.$refs.goodsAddInfoFormRef.resetFields();
        },
        resetPicsForm(){
            this.$refs.uploadPicsRef.clearFiles();
            this.pics = [];
        },
        toStaticForm(){
            this.$refs.goodsAddInfoFormRef.validate((valid)=>{
                if(valid){
                    this.actionPageStr = '2';
                    if(this.staticFormFirst){
                        this.staticFormFirst = false;
                        this.getgoodsStaticParams();
                    }
                }else{
                    return this.$message(
                        {
                            center:true,
                            showClose: true,
                            duration:2000,
                            message: '请填写商品基本信息！'
                        }
                    );
                }
            })            
        },
        toDynamicForm(){
            this.actionPageStr = '3';
            if(this.dynamicFormFirst){
                this.dynamicFormFirst = false;
                this.getgoodsDynamicParams();
            }
        },
        toUploadPicForm(){
            this.actionPageStr = '4';
            this.uploadPicsFormFirst = false;
        },
        toNextForm(){
            switch(this.actionPage){
                case 1:
                    this.toStaticForm()
                break;
                case 2:
                    this.toDynamicForm()
                break;
                case 3:
                    this.toUploadPicForm()
                break;
            }
        },
        backLastForm(){
            let backPage = parseInt(this.actionPageStr) - 1;
            this.actionPage = backPage;
            this.actionPageStr = backPage.toString();
        },
        checkAddGoodsCateForm(){
            this.goodsAddInfoForm.newGoodsCatePush = this.goodsAddInfoForm.newGoodsCate.join(',');

            this.goodsStaticParamsList.forEach(sItem => {
                const sInfo = {
                    attr_id: sItem.attr_id,
                    attr_value: sItem.attr_vals
                }
                this.attrs.push(sInfo);
            })
            this.goodsDynamicParamsList.forEach(dItem => {
                const dInfo = {
                    attr_id: dItem.attr_id,
                    attr_value: dItem.attr_vals.join(',')
                }
                this.attrs.push(dInfo);
            })

            this.pushAddGoodsCateForm();


        },
        async pushAddGoodsCateForm(){
            const { data: res } = await this.$http.post('goods',
                {
                    goods_name: this.goodsAddInfoForm.newGoodsName,
                    goods_cat: this.goodsAddInfoForm.newGoodsCatePush,
                    goods_price: this.goodsAddInfoForm.newGoodsPrice,
                    goods_number: this.goodsAddInfoForm.newGoodsNum,
                    goods_weight: this.goodsAddInfoForm.newGoodsWeight,
                    goods_introduce: this.goodsAddInfoForm.newGoodsCateIntroduce,
                    pics: this.pics,
                    attrs: this.attrs
                }
            );
            if(res.meta.status == 201){
                this.toFinshPage();
                return this.$message(
                    {
                        center:true,
                        showClose: true,
                        type: 'success',
                        duration:2000,
                        message: '添加商品成功！'
                    }
                )
            }else{
                return this.$message(
                    {
                        center:true,
                        showClose: true,
                        type: 'error',
                        duration:2000,
                        message: res.meta.msg
                    }
                )
            }
        },
        toFinshPage(){
            this.actionPageStr = '5';
            this.actionPage = 6;
            this.infoFormFirst = true;
            this.staticFormFirst = true;
            this.dynamicFormFirst = true;
            this.uploadPicsFormFirst = true;
            this.finishFormFirst = false;
            this.pics = [];
            this.attrs = [];
            setInterval(() => {
                if(this.countDown<=3 && this.countDown>0){
                    this.countDown--
                }
            }, 1000);
            setTimeout(() => {
                this.$router.push('/goods')
            }, 3500);
        },
    },
    watch:{
        'actionPageStr'(newValue){
            if(newValue=='5'){
                this.actionPage = 6;
            }else{
                this.actionPage = parseInt(newValue);
            }
        }
    },
    filters:{
        chooseColor(value){
            switch(value%3){
                case 0:
                    return 'color:#2b4b6b'
                break;
                case 1:
                    return 'color:#ffb417'
                break;
                case 2:
                    return 'color:#dd4f42'
                break;
            }
        }
    }
})
</script>

<style lang="less" scoped>
    .goodsAdd_container{
        width: 80vw;
        background-color: #fff;
        padding: 8px;
        margin:4vh auto;
        border-radius: 15px;
        box-shadow: 0 1px 15px #cbcbcb;
        h1{
            color: #3a2c3b;
            letter-spacing: 6px;
        }
        .taHeight{
            min-height:30vh;
            max-height:40vh;
            overflow-y: scroll;
        }
        .newFormButton{
            text-align: right;
            margin:0;
        }
        .bottomText{
            font-size: 14px;
            font-weight: bold;
        }
        .el-checkbox{
            margin:0;
            border-radius:100px;
        }
    }
    .picsPreview{
        z-index: 999;
        width: 100%;
        height: 100%;
        background-color: rgba(30,30,30,0.9);
        position: absolute;
        top: 0;
        left: 0;
        .closeBtn{
        position:absolute;
        top:0;
        right:24px;
        color:#f1f1f1;
        font-size:40px;
        font-weight:bold;
        transition:0.3s;
        }
        .closeBtn:hover,
        .closeBtn:focus{
        color:#bbb;
        cursor:pointer;
        }
        .image{
            width:70vw;
            position: absolute;
            top: 50%;
            left: 50%;
            transform:translate(-50%,-50%);
        }
    }
    ::-webkit-scrollbar
    {
        width: 0px;
        background-color: #F5F5F5;
    }

</style>